package com.ypf.rpc.nettyHandler;

import com.ypf.rpc.factory.RegisterFactory;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class RegisterHeartBeatServerHandler extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleState state = ((IdleStateEvent) evt).state();

            // 读空闲事件
            if (state==IdleState.READER_IDLE){
                RegisterFactory registerFactory = new RegisterFactory();
                for (int i = 0; i < RegisterFactory.registerFactory.size(); i++) {
                    if (RegisterFactory.registerFactory.get(i).getChannel().equals(ctx.channel())){  // 判断触发读空闲事件的通道是否为服务端通道
                        registerFactory.removeServer(ctx.channel());
                        i=i-1;
                        ctx.close();
                    }
                }

            }
        }else {
            super.userEventTriggered(ctx, evt);
        }

    }
}
